package io.github.GAIsad.repository;

import io.github.GAIsad.dto.CustomResult;
import io.github.GAIsad.util.MyDBUtil;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

public class DbRepository implements Repository {
    @Override
    public void store(List<CustomResult> results) {
        String insertSql = "insert into article(title, url, created_at, updated_at) values(?, ?, ?, ?);";


        for (CustomResult cr : results) {
            try {
                PreparedStatement pStmt = MyDBUtil.getConnection().prepareStatement(insertSql);
                pStmt.setString(1, cr.getTitle());
                pStmt.setString(2, cr.getUrl());
                pStmt.setString(3, cr.getCreatedAt());
                pStmt.setString(4, cr.getUpdatedAt());
                pStmt.executeUpdate();
            }  catch (SQLIntegrityConstraintViolationException e1) {
            if (e1.getMessage().contains("Duplicate entry")) {
                System.out.println("url(" + cr.getUrl() + ") 已经采集过了（可以只打印日志，也可以改做更新的操作）");
                // todo: 可以执行 update 语句
            } else {
                System.out.println("遇到了非 Duplicate entry 的约束，url(" + cr.getUrl() + ")");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
            }
        }
}

